//
//  HPSwiperService.m
//  HPZZTong
//
//  Created by wenjun on 14-5-6.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPSwiperService.h"
#import "HPBBPOSSwiper.h"
#import "HPZhijiaSwiper.h"
#import "ZZTongDefine.h"
#import "Utility.h"
#import "ZZTongClientEngine.h"
#import "ZZTongUtility.h"

static HPSwiperService * swiperService = nil;

@interface POSProcess()

- (void)start;

- (void)icQuestInputPin;

@end

@interface HPSwiperService()
{
    //音频刷卡器
    HPBBPOSSwiper * _bbposSwiper;
    HPZhijiaSwiper * _zhijiaSwiper;
    NSString * _encAmount;
}

@property (assign,nonatomic) HPBaseSwiper * currentSwiper;

@property (readonly,nonatomic) EncyptType encyptType;

@property (strong,nonatomic) NSString * swiperFactor;

@property (strong, nonatomic) SwiperComplete complete;

@property (nonatomic)SwiperType swiperType;

@end

@implementation HPSwiperService

+ (HPSwiperService *)sharedInstance
{
    if (!swiperService)
    {
        swiperService = [[super allocWithZone:NULL] init];
    }
    return swiperService;
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    return [self sharedInstance];
}

- (id)init
{
    self = [super init];
    _zhijiaSwiper = [HPZhijiaSwiper sharedInstance];
    [_zhijiaSwiper addObserver:self forKeyPath:@"connectState" options:NSKeyValueObservingOptionNew context:nil];
    
    _bbposSwiper = [HPBBPOSSwiper sharedInstance];
     [_bbposSwiper addObserver:self forKeyPath:@"connectState" options:NSKeyValueObservingOptionNew context:nil];
    
    _swiperType = SwiperTypeNone;
    
//    [NOTIFICATION addObserver:self selector:@selector(swiperSelectSucess:) name:SwiperSelectSuccessNotificationkey object:nil];
    return self;
}

- (void)swiperDisconnected
{
    [_zhijiaSwiper disconnect];
    [_bbposSwiper disconnect];
    _currentSwiper = nil;
    _csnStatus = CSNStatusNone;
    _encyptType = EncyptTypeNone;
    _swiperType = SwiperTypeNone;
    _swiperFactor = nil;
}

- (void)swiperSelectSucess:(NSNotification*)note{
    if (self.complete) {
        ExecuteSwiperBlock(self.complete, [HPSwiperResult successResult:SWIPERENG.csn]);
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"connectState"])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self connectStateChanged:[object connectState] swiper:object];
        });
    }
}

- (void)connectStateChanged:(SwiperState)connectState swiper:(HPBaseSwiper *)swiper
{
    SwiperState state = swiper.connectState;
    if (connectState == SwiperStateDectedDevice)
    {
        if (!self.currentSwiper || self.currentSwiper == swiper)
        {
            [self checkAndConnectSwiper:nil];
        }
    }
    if (swiper == self.currentSwiper)
    {
        
        [NOTIFICATION postNotificationName:SwiperStateChangeNotificationKey object:[NSNumber numberWithInteger:state]];
        if (connectState == SwiperStateNoDeviceDected || connectState == SwiperStateConnectFailed)
        {
            [self swiperDisconnected];
        }
        else if (connectState ==  SwiperStateConnected)
        {
            if (![CSNValidator isRunning])
            {
                [CSNValidator checkCSNStatus:nil autoTip:YES];
            }
        }
    }
}

- (void)selectSwiperAndGetCsn:(SwiperComplete)block isShow:(BOOL)show{
    if (show) {
        self.complete = block;
        [HPUIENG showScreen:SCR_SWIPER_SELECT];
        return;
    }
    if ([NSString isNilOrEmpty:self.csn]) {
        self.complete = block;
        [HPUIENG showScreen:SCR_SWIPER_SELECT];
    }else{
        self.complete = nil;
        ExecuteSwiperBlock(block, [HPSwiperResult successResult:self.csn]);
    }
}
- (void)changeSwiperType:(SwiperType)swiperType{
    
    SwiperComplete complete = ^(HPSwiperResult* swiperResult){
        if (swiperResult.isSuccess) {
            _swiperType = swiperType;
            if (self.complete) {
                ExecuteSwiperBlock(self.complete, swiperResult);
                self.complete = nil;
            }
        }else if(swiperResult.code == HPSwiperResultLowBattery){
            self.currentSwiper = nil;
            [HPUIENG showAlert:TipsLowBattery];
        }else{
            if ( self.currentSwiper.connectState == SwiperStateNoDeviceDected) {
                [HPUIENG showAlert:@"请插入刷卡器"];
            }
            
        }
    };
    if (swiperType != SwiperTypeNone && _swiperType == swiperType) {
        if ([NSString isNilOrEmpty:self.csn]) {
            [SwiperService checkAndConnectSwiper:complete];
        }else{
            ExecuteSwiperBlock(complete, [HPSwiperResult successResult:self.currentSwiper.ksn]);
        }
        
        return;
    }
    switch (swiperType) {
        case SwiperTypeBBPOS:{
            [_zhijiaSwiper stopOperation];
            [_bbposSwiper startOperation];
            _currentSwiper = _bbposSwiper;
            break;
        }
            
        case SwiperTypeZhijia:{
            [_bbposSwiper stopOperation];
            [_zhijiaSwiper startOperation];
            _currentSwiper = _zhijiaSwiper;
            break;
        }

            break;
        default:
            self.currentSwiper = nil;
            break;
    }
    [SwiperService checkAndConnectSwiper:complete];
}
- (void)checkAndConnectSwiper:(SwiperComplete)complete
{
    LOG(@"checkAndConnectSwiper：：%@",complete);
    if ([self.currentSwiper isConnected])
    {
        ExecuteSwiperBlock(complete, [HPSwiperResult successResult:self.currentSwiper.ksn]);
    }
    else
    {
        if (!complete) {
            complete = ^(HPSwiperResult *result) {
                if(result.code == HPSwiperResultLowBattery){
                    [HPUIENG showAlert:TipsLowBattery];
                }
            };
        }
//        self.currentSwiper = _zhijiaSwiper;
        [_currentSwiper getKSN:complete];
    }
}

- (SwiperComplete)addAction:(NSString *)action toCallBack:(SwiperComplete)complete
{
    if (complete)
    {
        SwiperComplete actionComplete = ^(HPSwiperResult * swiperResult)
        {
            [swiperResult setProperty:action forKey:@"action"];
            complete(swiperResult);
        };
        return actionComplete;
    }
    return nil;
}

- (void)doSwiper:(SwiperComplete)complete
{
    complete = [self addAction:SWIPER_SWIPE toCallBack:complete];
    [self.currentSwiper swipe:30*1000 factor:_swiperFactor complete:complete];
}

- (void)doEncyptPin:(NSString *)pin complete:(SwiperComplete)complete
{
    LOG(@"Encypt:%@",pin);
    complete = [self addAction:SWIPER_INPUT_PWD toCallBack:complete];
    [self.currentSwiper encryptPin:pin factor:_swiperFactor complete:complete];
}

- (void)doInputICPin:(NSString *)pin complete:(SwiperComplete)complete
{
    
}
- (void)doSelectApp:(NSArray*)type complete:(SwiperComplete)complete{
//    complete = [self addAction:SWIPER_SWIPE toCallBack:complete];
    [self.currentSwiper selectApp:type time:5 factor:_swiperFactor  complete:nil];
}
- (void)doInputPwdWithAmount:(NSString *)amount complete:(SwiperComplete)complete
{
    complete = [self addAction:SWIPER_INPUT_PWD toCallBack:complete];
    [_currentSwiper inputPwd:60 amount:amount factor:_swiperFactor complete:complete];
}

- (void)doMac:(NSString*)data complete:(SwiperComplete)complete
{
    complete = [self addAction:SWIPER_MAC toCallBack:complete];
    [self.currentSwiper encryptMac:data factor:_swiperFactor complete:complete];
}

- (BOOL)isCMBCSwiper:(NSString*)ksn
{
    if (ksn && (ksn.length > 4))
    {
        NSString* subStr = [ksn substringToIndex:4];
        if (subStr && [subStr.uppercaseString isEqualToString:@"CMBC"])
        {
            return YES;
        }
    }
    return NO;
}

- (NSString *)resetFactor
{
    _swiperFactor = [NSString stringWithFormat:@"%@80", [Utility getNowDateTime]];
    LOG(@"resetFactor:%@",_swiperFactor);
//    _swiperFactor = @"2014081413350980";
    return _swiperFactor;
}

- (NSString*)getFatorTime
{
    if (!_swiperFactor)
    {
        [self resetFactor];
    }
    return [_swiperFactor substringToIndex:(_swiperFactor.length -2)];
}

- (NSString *)csn
{
    return self.currentSwiper.ksn;
}

- (void)setCsnStatus:(CSNStatus)csnStatus
{
    _csnStatus = csnStatus;
}

- (BOOL)cancelSwiperOperation
{
    if ([_currentSwiper hasOperation])
    {
        [_currentSwiper cancelSwiperOperation];
        return YES;
    }
    return NO;
}

- (void)startProcess:(POSProcess *)process
{
    _currentProcess = process;
    _currentProcess.currentSwiper = _currentSwiper;
    [process start];
}

- (NSString *)icQuestInputPin
{
    dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
    dispatch_after(delayInNanoSeconds, dispatch_get_main_queue(), ^{
        [_currentProcess icQuestInputPin];
    });
    return _currentProcess.plainAmount;
}


@end
